package com.module.rotary.activity;

import android.animation.ValueAnimator;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Dialog;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.Nullable;

import com.dq.ad.AdManager;
import com.dq.ad.UMManager;
import com.dq.util.ILog;
import com.dq.util.NetWorkUtil;
import com.dq.util.ToastUtil;
import com.module.rotary.R;
import com.module.rotary.config.RotaryConfig;
import com.module.rotary.dialog.DialogResult;
import com.module.rotary.entity.RotaryEntity;
import com.module.rotary.listener.RotateListener;
import com.module.rotary.view.AutoTextView;
import com.module.rotary.view.WheelSurfView;

import org.litepal.LitePal;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

public class RotaryActivity extends Activity {

    private TextView tvTitle;
    private TextView tvActContent;
    private TextView tvLotteryNumber;
    private TextView tvCashRewards;
    private AutoTextView tvRadio;
    private Button btnVideo;
    private ImageView imgBack;
    private WheelSurfView wheelSurfView;

    private List<String> noticeContentList = new ArrayList<>();
    private static final int FLAG = 0x01;
    private EventHandler mEventHandler;
    private int mLoopCount = 0;
    private int mPosition = 0;

    @SuppressLint("WrongConstant")
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.M) {
            getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            getWindow().setStatusBarColor(Color.TRANSPARENT);
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
        }
        setContentView(R.layout.activity_rotary);
        initView();
    }

    @SuppressLint("SetTextI18n")
    private void initView() {

        tvTitle = findViewById(R.id.tvTitle);
        tvActContent = findViewById(R.id.tvActContent);
        tvLotteryNumber = findViewById(R.id.tvLotteryNumber);
        tvCashRewards = findViewById(R.id.tvCashRewards);
        btnVideo = findViewById(R.id.btnVideo);
        tvRadio = findViewById(R.id.tvRadio);
        imgBack = findViewById(R.id.imgBack);
        wheelSurfView = findViewById(R.id.wheelView);

        tvTitle.setText("免费抽奖");
        tvCashRewards.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG);

        if (!NetWorkUtil.isNetworkConnected(this)) {
            tvRadio.setVisibility(View.INVISIBLE);
        }

        String stringBuilder = "1.活动时间：即日起到2020-12-25\n" +
                "2.活动期间免费赠送一定数量的抽奖次数，每点击一次抽奖，即可抽奖一次。\n" +
                "3.转盘奖励：华为mate40手机、手机壳、话费充值券、华为蓝牙耳机、蓝牙音箱。每种奖品均须要集齐对应的碎片方可兑换，抽中每种碎片都有一定概率。若集齐5张不同的手机碎片，即可兑换大奖“华为mate40”（每个账号最多集齐1次）。奖品数量有限，领完为止。\n" +
                "4.集齐碎片之后需要手动兑换，兑换后的领取有效期为3日（含中奖当日）；请按照指引填写真实的收件人信息（个人信息仅用作快递信息使用），过期未填写视为放弃奖励；实物奖品将于活动结束15个工作日内寄出，如遇天气等不可抗因素，奖品发放可能延期。若由于用户原因导致奖品发放不成功，不再补发奖励。\n" +
                "5.观看视频可增加抽奖次数，看的越多，集齐碎片的机会就越大。\n" +
                "6.活动期间如果发现恶意刷奖行为，我方有权做封号处理，并取消抽奖以及获奖资格。\n" +
                "\n" +
                "该活动为免费活动，参与活动即表明你已知悉并同意以上活动规则说明，最终解释权归举办方所有。如有译文可以“我的-意见反馈”联系我们。\n";
        tvActContent.setText(stringBuilder);

        final String[] des = new String[]{"华为mate40手机", "手机壳", "话费充值券", "华为蓝牙手机", "蓝牙音箱", "再玩一次"};

        //添加滚动监听
        wheelSurfView.setRotateListener(new RotateListener() {
            @Override
            public void rotateEnd(int position, String desValue) {
                if (position == 1) {
                    desValue = "再玩一次";
                } else if (position == 2) {
                    desValue = "蓝牙音箱";
                } else if (position == 3) {
                    desValue = "华为蓝牙手机";
                } else if (position == 4) {
                    desValue = "话费充值券";
                } else if (position == 5) {
                    desValue = "手机壳";
                } else if (position == 6) {
                    desValue = "华为mate40手机";
                }
                ILog.e("抽奖结果:" + position + "," + desValue);
                position = getIndex(des, desValue) + 1;//数据库中对应商品的商品id
                wheelSurfView.mStart.setEnabled(true);  //圆盘转动过程中开始转动按钮需要禁止点击，转动结束解除禁止点击

                new DialogResult(RotaryActivity.this)
                        .setContent(desValue)
                        .setPos(position)
                        .then(new DialogResult.OnDialogClickLister() {
                            @Override
                            public void onClose(Dialog dialog) {
                                UMManager.onEvent(RotaryActivity.this,"Ad5Close");
                                dialog.dismiss();
                            }

                            @Override
                            public void onSeeVideo(Dialog dialog) {
                                UMManager.onEvent(RotaryActivity.this,"Ad5Pay");
                                dialog.dismiss();
                                AdManager.getInstance().showRewardVideoAD(RotaryActivity.this);
                            }

                            @Override
                            public void onReceive(Dialog dialog) {
                                UMManager.onEvent(RotaryActivity.this,"Ad5Close");
                                dialog.dismiss();
                            }
                        }).show();

                if (position == 6) {//再来一次
                    RotaryConfig.setLotteryNumber(RotaryConfig.getLotteryNumber() + 1);
                    updateLotteryNumber();
                    return;
                }

                List<RotaryEntity> entityList = LitePal.where("id = ?", String.valueOf(position)).find(RotaryEntity.class);
                if (entityList.size() > 0) {
                    RotaryEntity rotaryEntity = entityList.get(0);//抽中了某个商品（如mate40手机）

                    int debrisNumber = 0;//当前用户抽到的碎片数量
                    if (rotaryEntity.isSmoke1) {
                        debrisNumber++;
                    }
                    if (rotaryEntity.isSmoke2) {
                        debrisNumber++;
                    }
                    if (rotaryEntity.isSmoke3) {
                        debrisNumber++;
                    }
                    if (rotaryEntity.isSmoke4) {
                        debrisNumber++;
                    }
                    if (rotaryEntity.isSmoke5) {
                        debrisNumber++;
                    }

                    if (debrisNumber >= 4) {
                        //如果用户抽到4张碎片以后，禁止再继续抽取
                        return;
                    }

                    int random = new Random().nextInt(5) + 1;

                    switch (random) {
                        case 1:
                            rotaryEntity.setSmoke1(true);
                            break;
                        case 2:
                            rotaryEntity.setSmoke2(true);
                            break;
                        case 3:
                            rotaryEntity.setSmoke3(true);
                            break;
                        case 4:
                            rotaryEntity.setSmoke4(true);
                            break;
                        case 5:
                            rotaryEntity.setSmoke5(true);
                            break;
                    }
                    rotaryEntity.save();
                } else {
                    ToastUtil.showShortToast(RotaryActivity.this, "此次抽奖失败");
                }
            }

            @Override
            public void rotating(ValueAnimator valueAnimator) {

            }

            @Override
            public void rotateBefore(ImageView goImg) {

                UMManager.onEvent(RotaryActivity.this,"Ad4Pay");

                if (!NetWorkUtil.isNetworkConnected(RotaryActivity.this)) {
                    ToastUtil.showShortToast(RotaryActivity.this, "当前网络状态不佳，请检查网络后再试");
                    return;
                }

                /** 抽奖次数不够不再进行抽奖 **/
                if (RotaryConfig.getLotteryNumber() < 1) {
                    ToastUtil.showShortToast(RotaryActivity.this, "抽奖次数不够了，快去看视频吧！");
                    return;
                }

                /** 模拟位置 **/
                int position = new Random().nextInt(11);
                ILog.e("随机数:" + position);
                if (position > 6 || position == 2 || position == 0) {
                    position = 2;
                }
                ILog.e("最终结果:" + position);
                wheelSurfView.startRotate(position);

                /** 抽奖次数-1 **/
                RotaryConfig.setLotteryNumber(RotaryConfig.getLotteryNumber() - 1);
                updateLotteryNumber();

                wheelSurfView.mStart.setEnabled(false);
            }
        });

        initLister();
        updateLotteryNumber();
        initRadio();
    }

    public static int getIndex(String[] arr, String value) {
        for (int i = 0; i < arr.length; i++) {
            if (arr[i].equals(value)) {
                return i;                  //字符串时，换为 equals
            }
        }
        return 5;
    }

    private void initRadio() {
        noticeContentList.add("用户186****1586获得华为mate40一台");
        noticeContentList.add("用户152****4592获得蓝牙音箱一部");
        noticeContentList.add("用户176****3121获得100元话费券");
        noticeContentList.add("用户136****6875获得华为蓝牙耳机一副");
        noticeContentList.add("用户180****8036获得一个手机壳");
        noticeContentList.add("用户186****1586获得华为mate40一台");
        noticeContentList.add("用户152****4592获得华为蓝牙耳机一副");
        noticeContentList.add("用户176****3121获得华为mate40一台");
        noticeContentList.add("用户136****6875获得蓝牙音箱一部");
        noticeContentList.add("用户180****8036获得100元话费券");
        if (mEventHandler == null) {
            mEventHandler = new EventHandler();
        }
        mEventHandler.sendEmptyMessageDelayed(FLAG, 100);
    }

    @SuppressLint("HandlerLeak")
    public class EventHandler extends Handler {
        @Override
        public void handleMessage(android.os.Message msg) {
            if (msg.what == 0x01) {
                mPosition = mLoopCount % noticeContentList.size();
                tvRadio.next();
                tvRadio.setText(noticeContentList.get(mPosition));
                if (mLoopCount >= noticeContentList.size()) {
                    mLoopCount = 0;
                }
                mLoopCount++;
                mEventHandler.sendEmptyMessageDelayed(FLAG, 3000);
            }
        }
    }

    private void initLister() {
        imgBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        tvCashRewards.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                CashRewardsActivity.startAct(RotaryActivity.this);
            }
        });
        btnVideo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                UMManager.onEvent(RotaryActivity.this,"Ad6Pay");
                if (!NetWorkUtil.isNetworkConnected(RotaryActivity.this)) {
                    ToastUtil.showShortToast(RotaryActivity.this, "当前网络状态不佳，请检查网络后再试");
                    return;
                }
                AdManager.getInstance().showRewardVideoAD(RotaryActivity.this, new AdManager.OnRewardVideoADListener() {
                    @Override
                    public void onClosed() {
                        ILog.e("点击结束广告");
                    }

                    @Override
                    public void onReward() {
                        ILog.e("观看完毕");
                        RotaryConfig.setLotteryNumber(RotaryConfig.getLotteryNumber() + 1);
                        updateLotteryNumber();
                        ToastUtil.showShortToast(RotaryActivity.this, "恭喜您额外获得一次抽奖机会");
                    }

                    @Override
                    public void onFailed(int i, Object adError) {

                    }
                });
            }
        });
    }

    @SuppressLint("SetTextI18n")
    private void updateLotteryNumber() {
        tvLotteryNumber.setText("剩余抽奖次数:" + RotaryConfig.getLotteryNumber());
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mEventHandler != null) {
            mEventHandler.removeCallbacksAndMessages(null);
        }
    }
}